import { formatDate, isArray, jsonParse, setStore } from '@material/helpers';
import { isString } from '@tarojs/shared';
import { HistoryApiType, MessageInfo } from './type';

export const transformMessageItem = function (msgString: string, isHistory = false) {
    if (isString(msgString)) {
        const {
            Content: content,
            ExtInfo: extInfo,
            From: from,
            FromType: fromType,
            MsgType: msgType,
            Event: event,
            MsgTime: msgTime,
            MsgId: msgId
        } = jsonParse(msgString);
        return {
            Content: content,
            ExtInfo: extInfo,
            From: from,
            FromType: fromType,
            MsgType: msgType,
            Event: event,
            formateTime: formatDate(Number(msgTime) * 1000, 'YYYY-MM-DD hh:mm:ss'),
            MsgTime: msgTime,
            isHistory,
            MsgId: msgId
        } as unknown as MessageInfo;
    }
    return msgString;
};

const transformHistoryData = function (data: any) {
    if (isArray(data) && data.length) {
        return data.map((msgString) => {
            return transformMessageItem(msgString, true);
        });
    }
    return [];
};

export const getLastMessageId = function (dataList: any[]) {
    if (isArray(dataList) && dataList.length) {
        const lastItem = dataList[dataList.length - 1];
        return lastItem.MsgId;
    }
    return '';
};

export const getHistoryList = async function (historyApi: HistoryApiType, params: any) {
    const [err, data] = await historyApi({ ...params });
    if (err) {
        return [1, []];
    }
    const list = transformHistoryData(data);
    const id = getLastMessageId(list);
    if (id) {
        setStore('AI_Message_Last_id', id);
    }
    return [0, list];
};

export const aboveChatTime = function (data: MessageInfo[], expireTime: number) {
    const lastItem = isArray(data) && data.length ? data[data.length - 1] : null;
    if (!lastItem) {
        return true;
    }
    const diffTime = Date.now() - lastItem.MsgTime * 1000;
    const expireStamp = expireTime * 60 * 1000;
    if (diffTime - expireStamp < 0) {
        return false;
    }
    return true;
};
export const getLastMessageList = async function (
    historyApi: HistoryApiType,
    params: any
): Promise<[0 | 1, MessageInfo[]]> {
    const [err, data] = await historyApi({ count: 10, ...params });
    if (err) {
        return [1, []];
    }
    const list = transformHistoryData(data);
    if (Array.isArray(list) && list.length) {
        return [0, list];
    }
    return [0, []];
};
